Flow control

I want to make a bacon sandwhich.

How would I make a bacon sandwhich?

What if I don't like the end pieces?

What if I started a sandwhich factory and need to make thousands of them?

what if the only people who like end pieces like eating their sandwhiches with double end pieces!??

Computers are made to take a series of instructions and do something useful (or not). These algorithims are what make computers so useful! They allow computers to do what they do best, follow instructions and do them over and over again.

What happens if a decision has to be made?

The if/else statement - conditional

  • If the piece of bread is an end piece, skip it

What's nice about python is that a lot of the language can almost be read like english.

the only 'syntax' you have to deal with is tabs and a semi-colon

This is what an if statement looks like in python (in the general form)

if (some boolean value):
    do some stuff if the boolean is true

more on if elif else


In [16]:
if "daniel" == "daniel":
    print ":D"
print "i'm here!"


:D
i'm here!

in our bacon sandwhich example:

if (the slice of bread is an end piece):
    skip it
else:
    use bread to make sandwhich

In [41]:
#list_of_names = ["daniel", "niels", "vivian", "thomas"]

# how do i check if the fist name in the list is daniel?
if (list_of_names[0] == 'asdf'):
    print "yes it is"
    print "your name is daniel"

#print "no"


# how do i check if a name is in my list? if it is, print it!
if ("julia" in list_of_names):
    print "yes he is in there"
else:
    print "adding"
    list_of_names.append("julia")

print list_of_names

# if the name isn't add it to the list


adding
['daniel', 'niels', 'vivian', 'thomas', 'asdf', 'asdf', 'julia']

Loops

the for loop

computers are great at doing something over and over again, one way we can tell a computer to iterate through something is using a 'for' loop

the for loop looks like this:

for some_variable in some_iterable:
    do something

so, if we have an iterable (like a list), we can do something with each element in that list


In [12]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]

for letter in "daniel":
    if letter == "n":
        break
    print letter
print "hello"

'''
letter = "daniel"[0]
print letter

letter = "daniel"[1]
print letter
'''


d
a
hello
Out[12]:
'\nletter = "daniel"[0]\nprint letter\n\nletter = "daniel"[1]\nprint letter\n'

isn't that cool? now we don't have to change an index to get each one.

This brings us to a very important point:

  • you want to copy paste code as little as possible, more repetition in code, means when you have to change something, it will have to be corrected in many places, this can lead to mistakes (we will drive this point further in the next chapter)

In [5]:
# the 'name' variable in the previous example can be anything
# however you should use variable names so it is readable and 
# self documenting

# we could've easily have written the follow to do the same thing
# coconut

## todo write code here

the while loop

although not as common as the for loop, the while loop has a similar structure to the if statment. at the end of each cycle, the condition is re-evaluated. It will only exit the loop if the condition evaluates to false

be careful with while loops, it's possible to enter an infinite loop here.


In [5]:
# infinite while loop
flag = True
i = 0
while (flag):
    print i
    if i == 5:
        flag = False
    i += 1


0
1
2
3
4
5

I do not use while loops too much, you can pretty much accomplish the same thing using a for loop, however, sometimes i would use it if there are calculations to be done, and i know what case for it to stop in.

more flow control statements

the continue statment

Sometimes when you are doing loops, you know a certain value is an exception and should be skipped over but you still need to iterate through the loop. How do you manage this?

although you can add an if statment, once it leaves the if block, the program will still loop through the rest of the loop block,

the continue statment solves this issue

essentially it says, stop everythign here, and return to the top, and continue as usual.


In [ ]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]

# skip daniel but print the rest

# skip vivian, but print the rest

the break statement

Sometimes there is such an exception that you need to prematurely break out of the loop.


In [ ]:
list_of_names = ["daniel", "niels", "vivian", "thomas"]

'''
niels is the president of CSAPH, what if we had a list of names
but did not know where in the list he is?

we can loop through the list, and stop when we see his name
'''

Congratulations!

what you have learned until now are the very basic fundamentals to programming, everything you learn hear on out will build on this. It's amazing what you can accomplish with variables, data structures, conditionals, and loops

Let's keep building on conditionals and lists.

We want niel's name in the list, how would we get where his position is if we do not know it?


In [ ]:
# hint: loop and variables

In [ ]:
# let's write the same thing using a while() loop

Here's a fun question I wrote for Software Carpentry

here is pseudo code taken from wikipedia on how to calculate a leap year: I have numbered the lines

  1. if year is divisible by 400 then is_leap_year
  2. else if year is divisible by 100 then not_leap_year
  3. else if year is divisible by 4 then is_leap_year
  4. else not_leap_year

If i was counting from year 0 to 2014 where would I put a break statement so i stop counting after I encounter the first year that is divisible by 4 but still not be a leap year?

A. before line 1
B. after line 1
C. after line 2
D. after line 3
E. after line 4

Wasn't that fun? bet you didn't know that there's more to leap years than you thought!

Let's actually write something where we assign some number to a variable, and then test to see if it is a leap year or not


In [ ]:
## leap year code

You told us we learned the core material alreay, you promiced building patient data!

fine.

Let's go generate some data and read it in to python in some way.


In [7]:



/home/dchen/git/columbia/csaph-python/python-beginner

What if we are only interested in first names?


In [ ]:

Uh oh... how to we break apart the lines?

Do we see any kind of pattern?


In [ ]:
# string methods

Do we have enough to find first names now?


In [ ]:

Let's do some summary statistics


In [ ]:

What else can we do?

range()

I lied, this is pretty useful too.

let's play around with range()

what do you think range does?

what do you think range(10) does? or range(0,10), or range(5,10)


In [ ]:

Cool, let's have some mind teasers

link to swc questions

which of the following will only print “hello world” exactly 3 times?

A.

while(True):
   Print "hello world"

B.

for pizza in range(4):
  if pizza == 4:
       break
  else:
       print "hello world"

C.

for pizza in range(4):
    if pizza == 3:
        break
    else:
        print "hello world"
    if pizza == 2:
        continue

D.

for pizza in range(3):
      continue
      print "hello world"

E.

for pizza in range(3):
      continue
      print "hello world"
      break

F.

for pizza in range(4):
    if pizza == 3:
        break
    if pizza == 2:
        continue
    else:
        print "hello world"

In [ ]:

here is a MCQ that will test your understanding of loops, conditions, and flow control

You probably would never write code like this but take this as an example:

What will this script return in standard output?

flag = False
while (not flag):
    for pizza in range(5):
        print pizza
        if pizza == 5:
            print "stop feeding me i'm full"
        if pizza == 4:
            continue
        if pizza == 3:
            break
            flag = False
        if pizza == 2:
            flag = True
        if pizza == int(str(1)):
            print "more pizza please"
        else:
            continue
    break

A. this will return an infinite loop
B. the values 0, 1, more pizza please, 2, 3, 4, 5, stop feeding me i’m full on separate lines
C. the values 0, 1, more pizza please, 2, 3, 4 on separate lines
D. the values 0, 1, more pizza please, 2, 3, stop feeding me i’m full on separate lines
E. the values 0, 1, more pizza please, 2, 3 on separate lines
F. the values 0, 1, 2, 3, 4, 5 on separate lines
G. the values 0, 1, 2, 3, 4 on separate lines
H. this will return nothing


In [ ]:


In [88]:
with open('testdata.txt') as file:
    currentTotal = 0
    numberOfPeople = 0
    for line in file:
        print int(line.split(',')[2].rstrip('\n'))
        numberOfPeople += 1
        currentTotal += int(line.split(',')[2].rstrip('\n'))

    print "average: ", float(currentTotal)/numberOfPeople


63
56
55
70
69
67
67
69
62
68
60
70
70
64
64
50
65
71
34
63
74
50
67
65
average:  63.0416666667